{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a45466fd-4ff7-4c52-9de4-ecf3891b994a",
   "metadata": {},
   "source": [
    "Chapter 07\n",
    "# 复刻numpy.linspace() 基本功能\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "26d324b8-c026-425d-8a57-325e7453992a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自定义函数模仿 numpy.linspace()\n",
    "def linspace(start, stop, num=50, endpoint=True):\n",
    "    if num < 2:\n",
    "        # 报错\n",
    "        raise ValueError(\"Number of samples must be at least 2\")\n",
    "    # 是否包括右端点\n",
    "    if endpoint:\n",
    "        step = (stop - start) / (num - 1)\n",
    "        return [start + i * step for i in range(num)]\n",
    "    else:\n",
    "        step = (stop - start) / num\n",
    "        return [start + i * step for i in range(num)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2284ac5c-a5c2-4ba4-a692-3c0f3ef2b377",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例用法\n",
    "start = 0   # 数列起点\n",
    "stop  = 10  # 数列终点\n",
    "num   = 21  # 数列元素\n",
    "endpoint = True # 数列包含 stop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b912faac-c406-41b0-9b8c-d675b692a919",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 调用自定义函数生成等差数列\n",
    "values = linspace(start, stop, num, endpoint)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
